package com.ktjy.websocket;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{cid}")
public class WebSocketServer {
    static Map<String, Session> map=new HashMap<>();
    /**
     * 连接建立
     */
    @OnOpen
    public void onOpen(@PathParam("cid") String cid, Session session){
        map.put(cid,session);
    }
    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(@PathParam("cid") String cid){
        map.remove(cid);
    }
    /**
     * 收到客户信息
     */
    @OnMessage
    public void onMessage(@PathParam("cid") String cid,String message){
        System.out.println("客户端【"+cid+"】发送了："+message);
    }

    /**
     * 服务端群发消息给客户端
     * @param message
     * @throws IOException
     */
    public void send(String message) throws IOException {
        Collection<Session> values = map.values();
        for (Session session : values) {
            session.getBasicRemote().sendText(message);
        }
    }
}
